package com.jackstraw.jack_base.mq.rocketmq.bean.listener;

import com.jackstraw.jack_base.mq.rocketmq.bean.TrListenerEntity;
import com.jackstraw.jack_base.util.ObjectUtil;
import com.jackstraw.jack_base.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;


@Slf4j
@RocketMQTransactionListener
public class ProducerRocketMQLocalTransactionListener implements RocketMQLocalTransactionListener {

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        log.info("ProducerRocketMQLocalTransactionListener---Message:[{}]", msg);
        log.info("ProducerRocketMQLocalTransactionListener---Object:[{}]", arg);
        TrListenerEntity trListenerEntity = new TrListenerEntity();
        trListenerEntity.setSpringMessage(msg);
        trListenerEntity.setArg(arg);
        String producerTxServiceBeanName = String.valueOf(msg.getHeaders().get(ProducerTxService.PRODUCER_TX_SERVICE_BEAN_NAME));
        ProducerTxService producerTxService = SpringUtil.getBean(producerTxServiceBeanName, ProducerTxService.class);
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(producerTxService)) {
            log.error("ProducerRocketMQLocalTransactionListener#executeLocalTransaction---未找到处理事务的服务");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return producerTxService.executeLocalTransaction(trListenerEntity).getRocketMQLocalTransactionState();

    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        log.info("ProducerRocketMQLocalTransactionListener---Message:[{}]", msg);
        TrListenerEntity trListenerEntity = new TrListenerEntity();
        trListenerEntity.setSpringMessage(msg);
        String producerTxServiceBeanName = String.valueOf(msg.getHeaders().get(ProducerTxService.PRODUCER_TX_SERVICE_BEAN_NAME));
        ProducerTxService producerTxService = SpringUtil.getBean(producerTxServiceBeanName, ProducerTxService.class);
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(producerTxService)) {
            log.error("ProducerRocketMQLocalTransactionListener#checkLocalTransaction---未找到事务回查的服务");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return producerTxService.checkLocalTransaction(trListenerEntity).getRocketMQLocalTransactionState();
    }


}
